package com.tanovo.service.impl;

import com.aliyun.oss.OSSClient;
import com.tanovo.bo.FileBo;
import com.tanovo.exception.ServiceException;
import com.tanovo.service.IFileUploadService;
import com.tanovo.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadServiceImpl implements IFileUploadService {
    //阿里云绑定的域名
//    private String privateBucketUrl = "http://cloud-tanovo-private-test.oss-cn-hangzhou.aliyuncs.com";
//    private String publicBucketUrl = "http://cloud-tanovo-public-test1.oss-cn-hangzhou.aliyuncs.com";
    //阿里云路径前缀
    private final String aliyunPrefix = "tanovo";
    //阿里云EndPoint
    @Value("${ailiyun.oss.endpoint}")
    private String aliyunEndPoint;
    //阿里云AccessKeyId
    @Value("${ailiyun.oss.accesskey}")
    private String aliyunAccessKeyId;
    //阿里云AccessKeySecret
    @Value("${ailiyun.oss.accesskeysecret}")
    private String aliyunAccessKeySecret;
    //私有阿里云BucketName
    @Value("${ailiyun.oss.bucket.private}")
    private String privateAliyunBucketName;
    //公有阿里云BucketName
    @Value("${ailiyun.oss.bucket.public}")
    private String publicAliyunBucketName;


    private OSSClient client;

    @PostConstruct
    public void init() {
        client = new OSSClient(aliyunEndPoint, aliyunAccessKeyId, aliyunAccessKeySecret);
    }

    @Override
    public FileBo publicAliyunUpload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String prefix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String path = this.getPath(aliyunPrefix) + "." + prefix;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(file.getBytes());
            client.putObject(publicAliyunBucketName, path, byteArrayInputStream);
        } catch (Exception e) {
            log.error("阿里云上传文件出错", e);
            throw new ServiceException("阿里云上传文件出错");
        }
        long fileSize = file.getSize();
        FileBo fileBo = new FileBo();
        fileBo.setFileSize(fileSize);
        fileBo.setOriginalFilename(originalFilename);
        fileBo.setFileName(file.getName());
        fileBo.setPath(this.getBucketUrl(publicAliyunBucketName) + "/" + path);
        return fileBo;
    }

    @Override
    public FileBo privateAliyunUpload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String prefix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String path = this.getPath(aliyunPrefix) + "." + prefix;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(file.getBytes());
            client.putObject(privateAliyunBucketName, path, byteArrayInputStream);
        } catch (Exception e) {
            log.error("阿里云上传文件出错", e);
            throw new ServiceException("阿里云上传文件出错");
        }
        long fileSize = file.getSize();
        FileBo fileBo = new FileBo();
        fileBo.setFileSize(fileSize);
        fileBo.setOriginalFilename(originalFilename);
        fileBo.setFileName(file.getName());
        fileBo.setPath(path);
        return fileBo;
    }

    @Override
    public String getInternetUrl(String innerPath) {
        Date expiration = new Date(new Date().getTime() + 60 * 1000);
        URL url = client.generatePresignedUrl(privateAliyunBucketName, innerPath, expiration);
        return url.toString();
    }

    /**
     * 文件路径
     *
     * @param prefix 前缀
     * @return 返回上传路径
     */
    public String getPath(String prefix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + DateUtils.format(new Date(), "HHmmss") + uuid.substring(0, 5);
        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return path;
    }

    private String getBucketUrl(String bucketName){
        return "http://"+bucketName+"."+aliyunEndPoint;
    }

}
